package com.aliang.shopping.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.DES;
import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.exception.DataException;
import com.aliang.shopping.model.dto.common.UpdatePasswordDTO;

import java.util.Objects;

/**
 * 密码工具类
 */
public class PasswordUtil {

    private static final DES des = new DES(Mode.CTS, Padding.PKCS5Padding, "0CoJUm6Qyw8W8jud".getBytes(), "01020304".getBytes());

    /**
     * 加密
     *
     * @param password
     * @return
     */
    public static String encrypt(String password) {
        return des.encryptHex(password, CharsetUtil.CHARSET_UTF_8);
    }

    /**
     * 判断密码是否不一致
     *
     * @param target 加密的密码
     * @param source 未加密的密码
     * @return
     */
    public static boolean isNotEqual(String target, String source) {
        //解密密码
        String encrypted;
        try {
            encrypted = des.decryptStr(target);
        } catch (Exception e) {
            throw new DataException(ResultCodeEnum.PASSWORD_NOT_MATCH);
        }
        return !Objects.equals(source, encrypted);
    }


    //密码校验
    public static void validate(UpdatePasswordDTO updateDTO) {
        //必要字段校验
        if (BeanUtil.hasNullField(updateDTO)) {
            throw new DataException(ResultCodeEnum.DATA_LACK);
        }
        //密码长度检验
        if (StrUtil.length(updateDTO.getOldPassword()) < 8 || StrUtil.length(updateDTO.getNewPassword()) < 8 || StrUtil.length(updateDTO.getConfirmPassword()) < 8) {
            throw new DataException(ResultCodeEnum.PASSWORD_LENGTH_ERR);
        }
        //二次密码是否一致
        if (!StrUtil.equals(updateDTO.getNewPassword(), updateDTO.getConfirmPassword())) {
            throw new DataException(ResultCodeEnum.PASSWORD_NOT_SAME);
        }
    }
}
